<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	RTF class
*****/
class RTF
{
// Constructor
	function RTF($db, $vars = FALSE)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/wp/WPRTF.php");
		$this->wprtf = new WPRTF();
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/file/FILE.php");
		$this->file = new FILE($this->db);
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/cite/CITE.php");
		$this->cite = new CITE($this->db, $this->vars);
		include_once("core/file/export/EXPORTCOMMON.php");
		$this->common = new EXPORTCOMMON($this->db);
		include_once("core/user/USER.php");
		$this->user = new USER($this->db);
		$this->pString = '';
		$this->fontSizes = array(
					1 => 8, 2 => 10, 3 => 12, 4 => 14, 5 => 16, 6 => 18, 7 => 20, 8 => 22,
				);
		$this->fonts = array(
					1 => "Arial",
					2 => "Courier",
					3 => "Georgia",
					4 => "Helvetica",
					5 => "MS Sans Serif",
					6 => "MS Serif",
					7 => "Palatino",
					8 => "Tahoma",
					9 => "Trebuchet MS",
					10 => "Times New Roman",
					11 => "Verdana",
				);
		$this->ubi = array(
					1 => "Normal",
					2 => "Italics",
					3 => "Bold",
					4 => "Underline",
				);
		$this->ubiBib = array(
					1 => "Normal",
					2 => "Bold",
				);
		$this->indentTabs = array(1 => 0, 2 => 1, 3 => 2, 4 => 3);
		$this->cr = array(1 => 1, 2 => 2, 3 => 3, 4 => 4);
		$this->dividerCR = array(1 => 0, 2 => 1, 3 => 2, 4 => 3, 5 => 4);
// Perform some system admin
		$this->file->tidyFiles();
	}
// Display RTF export and format options
	function setup()
	{
		include_once("core/html/FORM.php");
		include_once("core/html/MISC.php");
		$this->template->setVar('heading', $this->messages->text("heading", "exportRtf"));
// Check we have a list to export
		if(!$sql = $this->session->getVar('sql_stmt'))
			$this->failure($this->errors->text("file", "noSql"));
// load the session
		$sessionVars = $this->session->getArray("exportRtf");
		$this->template->setVar('formStart', FORM::formHeader("exportRtf"));
		if($this->session->issetVar("exportRtf_bibliography"))
			$checked = $this->session->getVar("exportRtf_bibliography") ? 'CHECKED' : FALSE;
		else
			$checked = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
		$pString = $this->makeForm($checked, "bibliography", "bibliography");
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		if($this->session->issetVar("exportRtf_abstract"))
			$checked = $this->session->getVar("exportRtf_abstract") ? 'CHECKED' : FALSE;
		else
			$checked = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
		$pString .= $this->makeForm($checked, "abstract", "abstract");
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		if($this->session->issetVar("exportRtf_notes"))
			$checked = $this->session->getVar("exportRtf_notes") ? 'CHECKED' : FALSE;
		else
			$checked = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
		$pString .= $this->makeForm($checked, "notes", "notes");
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		$selected = $this->session->getVar("exportRtf_metadata");
		$metadata = array(0 => $this->messages->text("exportRtf", "metadataAll"), 
			1 => $this->messages->text("exportRtf", "metadataUser"));
		if($selected)
			$pString .= TABLE::td(FORM::selectedBoxValue(
			$this->messages->text("exportRtf", "metadata"), "exportRtf_metadata", 
			$metadata, $selected, 2));
		else
			$pString .= TABLE::td(FORM::selectFBoxValue(
			$this->messages->text("exportRtf", "metadata"), "exportRtf_metadata", 
			$metadata, 2));
		$selected = $this->session->getVar("exportRtf_metadataFullCite") ? TRUE : FALSE;
		$pString .= TABLE::td(FORM::checkbox($this->messages->text("exportRtf", "metadataFullCite"), 
			"exportRtf_metadataFullCite", $selected));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		if($this->session->issetVar("exportRtf_quotes"))
			$checked = $this->session->getVar("exportRtf_quotes") ? 'CHECKED' : FALSE;
		else
			$checked = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
		$pString .= $this->makeForm($checked, "quotes", "quotes", TRUE);
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		if($this->session->issetVar("exportRtf_paraphrases"))
			$checked = $this->session->getVar("exportRtf_paraphrases") ? 'CHECKED' : FALSE;
		else
			$checked = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
		$pString .= $this->makeForm($checked, "paraphrases", "paraphrases", TRUE);
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		if($this->session->issetVar("exportRtf_musings"))
			$checked = $this->session->getVar("exportRtf_musings") ? 'CHECKED' : FALSE;
		else
			$checked = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
		$pString .= $this->makeForm($checked, "musings", "musings");
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
// Entry divider
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		if(!$this->session->getVar("exportRtf_done"))
			$selected = '______________________________________________________________';
		else
			$selected = trim($this->session->getVar("exportRtf_divider"));
		$pString .= TABLE::td(FORM::textInput($this->messages->text("exportRtf", "divider"), 
			"exportRtf_divider", $selected, 75));
// Divider Font
		if(!$selected = $this->session->getVar("exportRtf_dividerFont"))
			$selected = 3; // Georgia
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "font"), 
			"exportRtf_dividerFont", $this->fonts, $selected, 3));
// Divider Font Size
		if(!$selected = $this->session->getVar("exportRtf_dividerFontSize"))
			$selected = 2; // 10
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "fontSize"), 
			"exportRtf_dividerFontSize", $this->fontSizes, $selected, 3));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
// Carriage returns after each entry
		if(!$selected = $this->session->getVar("exportRtf_dividerCR"))
			$selected = 4;
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "dividerCR"), 
			"exportRtf_dividerCR", $this->dividerCR, $selected, 3));
// preferences
		include_once("core/styles/LOADSTYLE.php");
		$styles = LOADSTYLE::loadDir("styles/bibliography");
		if($selected = $this->session->getVar("exportRtf_style"))
			$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("config", "style"), 
				"exportRtf_style", $styles, $this->session->getVar("exportRtf_style"), 4));
		else
			$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("config", "style"), 
				"exportRtf_style", $styles, $this->session->getVar("setup_style"), 4));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		if(sizeof($sessionVars) > 1) // by default, array has a single 'style' key (see above)
		{
			$this->session->clearArray("exportRtf");
			$this->session->setVar('exportRtf_style', $this->session->getVar("setup_style"));
			$reset = FORM::formHeader("exportRtfSetup") . 
				FORM::formSubmit("Reset") . FORM::formEnd();
			$pString .= MISC::p(FORM::formSubmit("Proceed") . FORM::formEnd() . $reset);
		}
		else
			$pString .= MISC::p(FORM::formSubmit("Proceed") . 
			MISC::br() . MISC::br() . FORM::formReset() . FORM::formEnd());
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// make a form subset for setup()
	function makeForm($checked, $session, $text, $comments = FALSE)
	{
		$pString = TABLE::tableStart();
		$pString .= TABLE::trStart();
		$temp = MISC::b($this->messages->text("exportRtf", $text)) . "&nbsp;" . 
			FORM::checkbox(FALSE, "exportRtf_" . $text, $checked);
		if($session != 'bibliography')
		{
			if(!$this->session->getVar("exportRtf_done"))
				$selected = $this->messages->text("exportRtf", $session . 'Tag');
			else
				$selected = trim($this->session->getVar("exportRtf_" . $session . "Tag"));
			$temp .= MISC::br() . FORM::textInput($this->messages->text("exportRtf", "tag"), 
				"exportRtf_" . $session . "Tag", $selected, 15);
		}
		$pString .= TABLE::td($temp);
		if($comments)
		{
			if($this->session->issetVar("exportRtf_" . $session . "Comments"))
				$checkedC = $this->session->getVar("exportRtf_" . $session . "Comments") ? 'CHECKED' : FALSE;
			else
				$checkedC = $this->session->issetVar("exportRtf_done") ? FALSE : 'CHECKED';
			$temp = $this->messages->text("exportRtf", "comments") . "&nbsp;" . 
				FORM::checkbox(FALSE, "exportRtf_" . $text . "Comments", $checkedC);
			if(!$selected = trim($this->session->getVar("exportRtf_" . $session . "CommentsTag")))
				$selected = $this->messages->text("exportRtf", $session . 'CommentTag');
			$temp .= MISC::br() . FORM::textInput($this->messages->text("exportRtf", "tag"), 
				"exportRtf_" . $session . "CommentsTag", $selected, 15);
			$pString .= TABLE::td($temp);
		}
// Font
		if(!$selected = $this->session->getVar("exportRtf_" . $session . "Font"))
			$selected = 3; // Georgia
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "font"), 
			"exportRtf_" . $session . "Font", $this->fonts, $selected, 3));
// Font Size
		if(!$selected = $this->session->getVar("exportRtf_" . $session . "FontSize"))
		{
			if($session == 'bibliography')
				$selected = 1; // 8
			else
				$selected = 2; // 10
		}
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "fontSize"), 
			"exportRtf_" . $session . "FontSize", $this->fontSizes, $selected, 3));
// Underline, Italics, Bold, Normal
		if($session != 'bibliography')
		{
			if($selected = $this->session->getVar("exportRtf_" . $session . "TextFormat"))
				$pString .= TABLE::td(FORM::selectedBoxValue(
				$this->messages->text("exportRtf", "textFormat"), "exportRtf_" . $session . "TextFormat", 
				$this->ubi, $selected, 3));
			else
				$pString .= TABLE::td(FORM::selectFBoxValue(
					$this->messages->text("exportRtf", "textFormat"), "exportRtf_" . $session . "TextFormat", 
					$this->ubi, 3));
		}
		else
		{
			if($selected = $this->session->getVar("exportRtf_bibliographyTextFormat"))
				$pString .= TABLE::td(FORM::selectedBoxValue(
					$this->messages->text("exportRtf", "textFormat"), "exportRtf_bibliographyTextFormat", 
					$this->ubiBib, $selected, 2));
			else
				$pString .= TABLE::td(FORM::selectFBoxValue(
					$this->messages->text("exportRtf", "textFormat"), "exportRtf_bibliographyTextFormat", 
					$this->ubiBib, 2));
		}
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= MISC::br() . "&nbsp;" . MISC::br();
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
// Left Indent
		if(!$selected = $this->session->getVar("exportRtf_" . $session . "IndentL"))
		{
			if($session != 'bibliography')
				$selected = 2; // 1
			else
				$selected = 1; // 0
		}
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "indentL"), 
			"exportRtf_" . $session . "IndentL", $this->indentTabs, $selected, 3));
// Right Indent
		if(!$selected = $this->session->getVar("exportRtf_" . $session . "IndentR"))
		{
			if(($session == 'abstract') || ($session == 'notes'))
				$selected = 2; // 1
			else if($session != 'bibliography')
				$selected = 1; // 2
			else
				$selected = 1; // 0
		}
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "indentR"), 
			"exportRtf_" . $session . "IndentR", $this->indentTabs, $selected, 3));
		if(($session == 'musings') || ($session == 'quotes') || ($session == 'paraphrases'))
		{
// Carriage Returns between parts of element
			if(!$selected = $this->session->getVar("exportRtf_" . $session . "CrBetween"))
				$selected = 2; // 1
			$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "crBetween"), 
				"exportRtf_" . $session . "CrBetween", $this->cr, $selected, 3));
		}
// Carriage Returns after element
		if(!$selected = $this->session->getVar("exportRtf_" . $session . "CrFollowing"))
			$selected = 2; // 1
		$pString .= TABLE::td(FORM::selectedBoxValue($this->messages->text("exportRtf", "crFollowing"), 
			"exportRtf_" . $session . "CrFollowing", $this->cr, $selected, 3));
// ISBN and Keywords and hyperlink
		if($session == 'bibliography')
		{
			$checkedC = $this->session->issetVar("exportRtf_bibliographyIsbn") ? 'CHECKED' : FALSE;
			$pString .= TABLE::td($this->messages->text("exportRtf", "isbn") . "&nbsp;" . 
				FORM::checkbox(FALSE, "exportRtf_bibliographyIsbn", $checkedC));
			$checkedC = $this->session->issetVar("exportRtf_bibliographyKeywords") ? 'CHECKED' : FALSE;
			$pString .= TABLE::td($this->messages->text("exportRtf", "keywords") . "&nbsp;" . 
				FORM::checkbox(FALSE, "exportRtf_bibliographyKeywords", $checkedC));
			$checkedC = $this->session->issetVar("exportRtf_link") ? 'CHECKED' : FALSE;
			$pString .= TABLE::td($this->messages->text("misc", "exportHyperlink") . "&nbsp;" . 
				FORM::checkbox(FALSE, "exportRtf_link", $checkedC));
		}
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		return $pString;
	}
// RTF header
	function rtfHeader()
	{
		$this->pString .= "{\\rtf1\\ansi\\deff0\n\n";
// blue for hyperlinks
		$this->pString .= "{\\colortbl;\\red0\\green0\\blue255;}\n\n";
// Stylesheet for hyperlinks, list bullets and endnotes
		$this->pString .= "\n{\\stylesheet\n{\\*\\cs1 Hyperlink;}\n{\\*\\cs1 Bullet Symbols;}\n{\\*\\cs1 Numbering Symbols;}\n{\*\cs16 \additive \sbasedon10 endnote reference;}\n}\n" . "\\aftnnar\\fet1\n\n";
	}
// RTF Footer
	function rtfFooter()
	{
		$this->pString .= "\\qj\\li0\\ri0\n\\par\n\n}";
	}
// RTF header fontBlocks
	function rtfFontBlock($type, $font, $fontSize, $indentL, $indentR, $crFollowing, $crBetween = FALSE, $textFormat = 'Normal')
	{
		if(!isset($this->fontBlockIndex))
			$this->fontBlockIndex = 0;
		$this->pString .= "{\\f" . $this->fontBlockIndex . "\\fcharset0 $font;}\n";
		$this->fontBlocks[$type]['fontBlock'] = "\\f" . $this->fontBlockIndex;
// Actual font size seems to be half this value and rounded up to an even number
		$this->fontBlocks[$type]['fontSize'] = "\\fs" . $fontSize * 2;
// Each TAB approximately = 720 (no idea what the units are)
		if($indentL)
			$this->fontBlocks[$type]['indentL'] = "\\li" . $indentL * 720;
		else
			$this->fontBlocks[$type]['indentL'] = "\\li0";
		if($indentR)
			$this->fontBlocks[$type]['indentR'] = "\\ri" . $indentR * 720;
		else
			$this->fontBlocks[$type]['indentR'] = "\\ri0";
		$this->fontBlocks[$type]['crFollowing'] = $crFollowing;
		if($crBetween)
			$this->fontBlocks[$type]['crBetween'] = $crBetween;
		if($textFormat != 'Normal')
			$this->fontBlocks[$type]['textFormat'] = $textFormat;
		$this->fontBlockIndex++;
	}
// RTF Paragraph block
	function rtfParagraphBlock($type)
	{
		if($type == 'divider')
			$pString = "{" . $this->fontBlocks[$type]['fontBlock'] . $this->fontBlocks[$type]['fontSize'];
		else
			$pString = "{" . $this->fontBlocks[$type]['fontBlock'] . $this->fontBlocks[$type]['fontSize'];
		if(array_key_exists('textFormat', $this->fontBlocks[$type]) && ($this->fontBlocks[$type]['textFormat'] == 'Italics'))
			$pString .= "\\i";
		else if(array_key_exists('textFormat', $this->fontBlocks[$type]) && 
			($this->fontBlocks[$type]['textFormat'] == 'Underline'))
			$pString .= "\\ul";
		if(array_key_exists('textFormat', $this->fontBlocks[$type]) && ($this->fontBlocks[$type]['textFormat'] == 'Bold'))
			$pString .= "\\b";
		$pString .= " ";
		return $pString;
	}
// make RTF fontBlocks according to input
	function makeFontBlocks()
	{
		$sqlSelectReplace = "SELECT ";
		$sqlJoinReplace = "FROM " . $this->db->formatTable('WKX_resource');
		$replace = FALSE;
		$this->pString .= "{\\fonttbl\n";
		if(array_key_exists("divider", $this->input))
		{
			$this->rtfFontBlock("divider", $this->fonts[$this->input['dividerFont']], 
				$this->fontSizes[$this->input['dividerFontSize']], 
				FALSE, FALSE, 0);
		}
		if(array_key_exists("bibliography", $this->input))
		{
			$this->rtfFontBlock("bibliography", $this->fonts[$this->input['bibliographyFont']], 
				$this->fontSizes[$this->input['bibliographyFontSize']], 
				$this->indentTabs[$this->input['bibliographyIndentL']],
				$this->indentTabs[$this->input['bibliographyIndentR']],
				$this->cr[$this->input['bibliographyCrFollowing']],
				FALSE, 
				$this->ubiBib[$this->input['bibliographyTextFormat']]);
		}
		if(array_key_exists("abstract", $this->input))
		{
			$this->rtfFontBlock("abstract", $this->fonts[$this->input['abstractFont']], 
				$this->fontSizes[$this->input['abstractFontSize']],
				$this->indentTabs[$this->input['abstractIndentL']],
				$this->indentTabs[$this->input['abstractIndentR']],
				$this->cr[$this->input['abstractCrFollowing']],
				FALSE, 
				$this->ubi[$this->input['abstractTextFormat']]);
			$sqlSelectReplace .= $this->db->formatField('abstract') . ", ";
// Select and Search operations already have WKX_abstract as part of SQL statement - need to add to list and basket operations
			if(($this->session->getVar('sql_lastMulti') == 'list') || 
				($this->session->getVar('sql_lastMulti') == 'listKeyword') ||
				($this->session->getVar('sql_lastMulti') == 'listPublisher') ||
				($this->session->getVar('sql_lastMulti') == 'listCollection') ||
				($this->session->getVar('sql_lastMulti') == 'listCategory') ||
				($this->session->getVar('sql_lastMulti') == 'listCite') ||
				($this->session->getVar('sql_lastMulti') == 'basket'))
				$sqlJoinReplace .= " LEFT JOIN " . $this->db->formatTable('WKX_resource_abstract') . 
					" ON " . $this->db->formatField('WKX_resource_abstract.id') . " = " . 
					$this->db->formatField('WKX_resource.id');
			$replace = TRUE;
		}
		if(array_key_exists("notes", $this->input))
		{
			$this->rtfFontBlock("notes", $this->fonts[$this->input['notesFont']], 
				$this->fontSizes[$this->input['notesFontSize']],
				$this->indentTabs[$this->input['notesIndentL']],
				$this->indentTabs[$this->input['notesIndentR']],
				$this->cr[$this->input['notesCrFollowing']],
				FALSE, 
				$this->ubi[$this->input['notesTextFormat']]);
			$sqlSelectReplace .= $this->db->formatAlias(array('WKX_resource_note.text' => 'notes')) . ", ";
			$replace = TRUE;
		}
		if(array_key_exists("quotes", $this->input))
			$this->rtfFontBlock("quotes", $this->fonts[$this->input['quotesFont']], 
				$this->fontSizes[$this->input['quotesFontSize']],
				$this->indentTabs[$this->input['quotesIndentL']],
				$this->indentTabs[$this->input['quotesIndentR']],
				$this->cr[$this->input['quotesCrFollowing']],
				$this->cr[$this->input['quotesCrBetween']],
				$this->ubi[$this->input['quotesTextFormat']]);
		if(array_key_exists("paraphrases", $this->input))
			$this->rtfFontBlock("paraphrases", $this->fonts[$this->input['paraphrasesFont']], 
				$this->fontSizes[$this->input['paraphrasesFontSize']],
				$this->indentTabs[$this->input['paraphrasesIndentL']],
				$this->indentTabs[$this->input['paraphrasesIndentR']],
				$this->cr[$this->input['paraphrasesCrFollowing']],
				$this->cr[$this->input['paraphrasesCrBetween']],
				$this->ubi[$this->input['paraphrasesTextFormat']]);
		if(array_key_exists("musings", $this->input))
			$this->rtfFontBlock("musings", $this->fonts[$this->input['musingsFont']], 
				$this->fontSizes[$this->input['musingsFontSize']],
				$this->indentTabs[$this->input['musingsIndentL']],
				$this->indentTabs[$this->input['musingsIndentR']],
				$this->cr[$this->input['musingsCrFollowing']],
				$this->cr[$this->input['musingsCrBetween']],
				$this->ubi[$this->input['musingsTextFormat']]);
		$this->pString .= "}\n\n";
		$sqlSelectDistinctReplace = str_replace('SELECT ', 'SELECT DISTINCT ', $sqlSelectReplace);
		return array($replace, $sqlSelectReplace, $sqlSelectDistinctReplace, $sqlJoinReplace);
	}
// encode paragraphs from HTML
	function paragraph($string)
	{
        	return preg_replace("/<\/ br>/i", "__WIKINDX__NEWLINEPAR__", $string);
	}
// write $this->pString to file.  If file exists, it is written over.
	function process()
	{
		$this->template->setVar('heading', $this->messages->text("heading", "exportRtf"));
		$this->input = $this->checkInput();
		$this->fontBlocks = array();
		$this->rtfHeader();
		$this->getData();
		$this->rtfFooter();
		list($fileName, $fullFileName) = $this->file->createFileName($this->pString, '.rtf');
		if(!$fullFileName)
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		if(!$fp = fopen("$fullFileName", "w"))
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		if(!fputs($fp, $this->pString))
			$this->failure($this->errors->text("file", "write", ": $fileName"));
		fclose($fp);
		$this->common->writeFilenameToSession($fileName);
		$pString = $this->common->listFiles();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// get data from database
	function getData()
	{
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($this->db, "rtf");
		if(!$sql = $this->session->getVar('sql_stmt'))
			$this->failure($this->errors->text("file", "noSql"));
		$userId = $this->session->getVar("setup_userId");
		$sql = stripslashes($sql);
		list($replace, $sqlSelectReplace, $sqlSelectDistinctReplace, $sqlJoinReplace) = $this->makeFontBlocks();
		if($replace)
		{
			if(strpos($sql, 'SELECT DISTINCT ') !== FALSE)
				$sql = str_replace("SELECT DISTINCT ", $sqlSelectDistinctReplace, $sql);
			else
				$sql = str_replace("SELECT", $sqlSelectReplace, $sql);
			$originalString = "FROM " . $this->db->formatTable("WKX_resource");
			$sql = str_replace($originalString, $sqlJoinReplace, $sql);
		}
		if(array_key_exists('link', $this->input))
		{
			global $_SERVER;
			$link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . "?action=resourceView&id=";
			$this->session->setVar('exportRtf_link', TRUE);
		}
		else
		{
			$link = FALSE;
			$this->session->delVar('exportRtf_link');
		}
		$recordset = $this->db->query($sql);
		while($row = $this->db->loopRecordSet($recordset))
		{
			$somethingToPrint = FALSE;
			$returnAfterBib = FALSE;
			if(array_key_exists('metadataFullCite', $this->input))
				$this->getFullCite($row['resourceId'], $row['type']);
			if(array_key_exists('bibliography', $this->input))
			{
				$this->pString .= $this->makeBlock('bibliography');
				$this->pString .= $this->rtfParagraphBlock('bibliography');
				$this->pString .= $this->paragraph($this->utf8_2_unicode($bibStyle->process($row)));
				if(array_key_exists('bibliographyIsbn', $this->input) && ($row['isbn']))
					$this->pString .= "  [" . $row['isbn'] . "]";
				if($link)
				{
					$hyperlink = $link . $row['resourceId'];
					$this->pString .= "{\\field{\\fldinst { HYPERLINK \"$hyperlink\" }}{\\fldrslt { [*]}}}";
				}
				$this->pString .= " }\n";
				if(array_key_exists('bibliographyKeywords', $this->input))
				{
					$recordset2 = $this->db->select(array('WKX_resource_keyword'), array('keywords'), 
						' WHERE ' . $this->db->formatField('id') . '=' . $this->db->tidyInput($row['resourceId']));
					if($keywordString = $this->db->fetchOne($recordset2))
					{
						foreach(split(',', $keywordString) as $keyword)
							$keywords[] = $this->db->tidyInput($keyword);
						$condition = $this->db->formatField('id') . "=" . join(" OR " .
							$this->db->formatField('id') . "=", $keywords);
						$recordset2 = $this->db->select(array('WKX_keyword'), array("keyword"), 
							" WHERE " . $condition . " ORDER BY " . $this->db->formatField('keyword'));
						$keywordStringArray = array();
						while($line = $this->db->loopRecordSet($recordset2))
							$keywordStringArray[] = $this->utf8_2_unicode(stripslashes($line['keyword']));
						$this->pString .= $this->makeParagraph('bibliography') . "\n";
						$this->pString .= $this->makeBlock('bibliography');
						$this->pString .= $this->rtfParagraphBlock('bibliography');
						$this->pString .= $this->paragraph('Keywords:    ' . join('  ', $keywordStringArray));
						$this->pString .= " }\n";
					}
				}
				for($i = 0; $i < $this->fontBlocks['bibliography']['crFollowing']; $i++)
					$this->pString .= $this->makeParagraph('bibliography') . "\n";
				$returnAfterBib = TRUE;
				$somethingToPrint = TRUE;
			}
			if(array_key_exists('abstract', $this->input) && $row['abstract'])
			{
				$this->pString .= $this->makeBlock('abstract');
				if($row['abstract'])
				{
					if($returnAfterBib)
					{
						$this->pString .= $this->makeParagraph('bibliography') . "\n";
						$returnAfterBib = FALSE;
					}
					if(trim($this->input['abstractTag']))
					{
						$this->pString .= $this->rtfParagraphBlock('abstract');
						$this->pString .= $this->utf8_2_unicode(trim($this->input['abstractTag'])) . 
							" \\par }\n";
					}
					$this->pString .= $this->rtfParagraphBlock('abstract');
					$this->pString .= $this->utf8_2_unicode($this->textFormat($row['abstract'], 
						'abstract')) . "}";
					for($i = 0; $i < $this->fontBlocks['abstract']['crFollowing']; $i++)
						$this->pString .= $this->makeParagraph('abstract') . "\n";
					$somethingToPrint = TRUE;
				}
			}
			if(array_key_exists('notes', $this->input) && $row['notes'])
			{
				$this->pString .= $this->makeBlock('notes');
				if($row['notes'])
				{
					if($returnAfterBib)
					{
						$this->pString .= $this->makeParagraph('bibliography') . "\n";
						$returnAfterBib = FALSE;
					}
					if(trim($this->input['notesTag']))
					{
						$this->pString .= $this->rtfParagraphBlock('notes');
						$this->pString .= $this->utf8_2_unicode(trim($this->input['notesTag'])) . 
							" \\par }\n";
					}
					$this->pString .= $this->rtfParagraphBlock('notes');
					$this->pString .= $this->utf8_2_unicode($this->textFormat($row['notes'], 
						'notes')) . "}";
					for($i = 0; $i < $this->fontBlocks['notes']['crFollowing']; $i++)
						$this->pString .= $this->makeParagraph('notes') . "\n";
					$somethingToPrint = TRUE;
				}
			}
			if(array_key_exists('musings', $this->input))
			{
				$this->pString .= $this->makeBlock('musings');
				if($this->input['metadata'] == 1) // only my musings
					$recordset2 = $this->db->select(array('WKX_resource_musing'), 
						array('page_start', 'page_end', 'text', 'addUserIdMusing'), 
						" LEFT JOIN " . $this->db->formatTable('WKX_resource_musing_text') . 
						" ON " . 
						$this->db->formatfield("WKX_resource_musing.id") . "=" . 
						$this->db->formatfield("WKX_resource_musing_text.id") . 
						" WHERE " . $this->db->formatfield("WKX_resource_musing.resourceId") . "=" . 
						$this->db->tidyInput($row['resourceId']) . 
						" AND " . 
						$this->db->formatfield("WKX_resource_musing_text.addUserIdMusing") . "=" . 
						$this->db->tidyInput($userId) . 
						" ORDER BY " . $this->db->tidyInputClause('page_start') . ' + 0');
				else // my musings and all public musings
					$recordset2 = $this->db->select(array('WKX_resource_musing'), 
						array('page_start', 'page_end', 'text', 'addUserIdMusing'), 
						" LEFT JOIN " . $this->db->formatTable('WKX_resource_musing_text') . 
						" ON " . 
						$this->db->formatfield("WKX_resource_musing.id") . "=" . 
						$this->db->formatfield("WKX_resource_musing_text.id") . 
						" WHERE " . $this->db->formatfield("WKX_resource_musing.resourceId") . "=" . 
						$this->db->tidyInput($row['resourceId']) . 
						" AND (" . 
						$this->db->formatfield("WKX_resource_musing_text.addUserIdMusing") . "=" . 
						$this->db->tidyInput($userId) . 
						" OR " . 
						$this->db->formatfield("WKX_resource_musing_text.musingPrivate") . "=" . 
						$this->db->tidyInput('N') . 
						") ORDER BY " . $this->db->tidyInputClause('page_start') . ' + 0');
//					ORDER BY " . $this->db->tidyInputClause('page_start')) . " + 0";
				if($this->db->numRows($recordset2))
				{
					if($returnAfterBib)
					{
						$this->pString .= $this->makeParagraph('bibliography') . "\n";
						$returnAfterBib = FALSE;
					}
					if(trim($this->input['musingsTag']))
					{
						$this->pString .= $this->rtfParagraphBlock('musings');
						$this->pString .= $this->utf8_2_unicode(trim($this->input['musingsTag'])) . 
							" \\par }\n";
					}
					$numElements = 0;
					while($rowT = $this->db->loopRecordset($recordset2))
					{
						$cite = "-->  "; // resetting
						$page_start = $rowT['page_start'] ? "p." . $rowT['page_start'] : FALSE;
						$page_end = $rowT['page_end'] ? "-" . $rowT['page_end'] : FALSE;
						if($page_start && $page_end)
							$page_start = 'p' . $page_start;
						if(array_key_exists('metadataFullCite', $this->input) && $this->fullCite && $page_start)
							$page_start = $this->fullCite . ', ' . $page_start;
						else if(array_key_exists('metadataFullCite', $this->input) && $this->fullCite)
							$page_start = $this->fullCite;
						if($page_start)
							$cite = "$page_start$page_end:  ";
						if($numElements)
							for($i = 0; $i < $this->fontBlocks['musings']['crBetween']; $i++)
								$this->pString .= $this->makeParagraph('musings') . "\n";
						$user = $this->user->displayUserAddEditPlain($rowT['addUserIdMusing']) . "\n";
						$this->pString .= $this->rtfParagraphBlock('musings');
						$this->pString .= $cite . $this->utf8_2_unicode($this->textFormat(
							$rowT['text'], 'musings')) . " ($user)\\par }";
						$numElements++;
					}
					for($i = 0; $i < $this->fontBlocks['musings']['crFollowing']; $i++)
						$this->pString .= $this->makeParagraph('musings') . "\n";
					$somethingToPrint = TRUE;
				}
			}
			if(array_key_exists('quotes', $this->input))
			{
				$this->pString .= $this->makeBlock('quotes');
				$recordset2 = $this->db->select(array('WKX_resource_quote'), 
						array(array('WKX_resource_quote.id' => 'quoteId'), 
							'page_start', 'page_end', 'text'), 
						" LEFT JOIN " . $this->db->formatTable('WKX_resource_quote_text') . 
						" ON " . $this->db->formatField("WKX_resource_quote.id") . "=" . 
						$this->db->formatField("WKX_resource_quote_text.id") . 
						" WHERE " . $this->db->formatField("WKX_resource_quote.resourceId") . "=" . 
						$this->db->tidyInput($row['resourceId']) . 
						" ORDER BY " . $this->db->tidyInputClause('page_start') . ' + 0');
//						ORDER BY " . $this->db->tidyInputClause('page_start')) . " + 0";
				if($this->db->numRows($recordset2))
				{
					if($returnAfterBib)
					{
						$this->pString .= $this->makeParagraph('bibliography') . "\n";
						$returnAfterBib = FALSE;
					}
					if(trim($this->input['quotesTag']))
					{
						$this->pString .= $this->rtfParagraphBlock('quotes');
						$this->pString .= $this->utf8_2_unicode(trim($this->input['quotesTag'])) . 
							" \\par }\n";
					}
					$numElements = 0;
					while($rowT = $this->db->loopRecordSet($recordset2))
					{
						$cite = "-->  "; // resetting
						$page_start = $rowT['page_start'] ? "p." . $rowT['page_start'] : FALSE;
						$page_end = $rowT['page_end'] ? "-" . $rowT['page_end'] : FALSE;
						if($page_start && $page_end)
							$page_start = 'p' . $page_start;
						if(array_key_exists('metadataFullCite', $this->input) && $this->fullCite && $page_start)
							$page_start = $this->fullCite . ', ' . $page_start;
						else if(array_key_exists('metadataFullCite', $this->input) && $this->fullCite)
							$page_start = $this->fullCite;
						if($page_start)
							$cite = "$page_start$page_end:  ";
						if($numElements)
							for($i = 0; $i < $this->fontBlocks['quotes']['crBetween']; $i++)
								$this->pString .= $this->makeParagraph('quotes') . "\n";
						$this->pString .= $this->rtfParagraphBlock('quotes');
						$this->pString .= $cite . $this->utf8_2_unicode($this->textFormat(
							$rowT['text'], 'quotes')) . "\\par }";
						if(array_key_exists('quotesComments', $this->input))
						{
							if($this->input['metadata'] == 1) // only my musings
								$recordset3 = $this->db->select(array('WKX_resource_quote_comment'),
									array('comment', 'addUserIdQuote'), 
									" WHERE " . $this->db->formatField('quoteId') . "=" . 
									$this->db->tidyInput($rowT['quoteId']) . 
									" AND " . 
									$this->db->formatfield("addUserIdQuote") . "=" . 
									$this->db->tidyInput($userId));
							else // my musings and all public musings
								$recordset3 = $this->db->select(array('WKX_resource_quote_comment'),
									array('comment', 'addUserIdQuote'), 
									" WHERE " . $this->db->formatField('quoteId') . "=" . 
									$this->db->tidyInput($rowT['quoteId']) . 
									" AND (" . 
									$this->db->formatfield("addUserIdQuote") . "=" . 
									$this->db->tidyInput($userId) . 
									" OR " . 
									$this->db->formatfield("quotePrivate") . "=" . 
									$this->db->tidyInput('N') . ")"
									);
							while($rowC = $this->db->loopRecordset($recordset3))
							{
								$user = $this->user->displayUserAddEditPlain($rowC['addUserIdQuote']) . "\n";
								if(trim($this->input['quotesCommentsTag']))
								{
									$this->pString .= "\n" . 
										$this->rtfParagraphBlock('quotes');
									$this->pString .= $this->utf8_2_unicode(trim(
										$this->input['quotesCommentsTag'])) . 
										"  }\n";
								}
								$this->pString .= $this->rtfParagraphBlock('quotes');
								$this->pString .= $this->utf8_2_unicode(
								$this->textFormat($rowC['comment'], 'quotes')) . 
									"  ($user)\\par }\n";
							}
						}
						$numElements++;
					}
					for($i = 0; $i < $this->fontBlocks['quotes']['crFollowing']; $i++)
						$this->pString .= $this->makeParagraph('quotes') . "\n";
					$somethingToPrint = TRUE;
				}
			}
			if(array_key_exists('paraphrases', $this->input))
			{
				$this->pString .= $this->makeBlock('paraphrases');
				$recordset2 = $this->db->select(array('WKX_resource_paraphrase'), 
					array(array('WKX_resource_paraphrase.id' => 'paraphraseId'), 
					'page_start', 'page_end', 'text'), 
						" LEFT JOIN " . $this->db->formatTable('WKX_resource_paraphrase_text') . 
						" ON " . $this->db->formatField("WKX_resource_paraphrase.id") . "=" . 
						$this->db->formatField("WKX_resource_paraphrase_text.id") . 
						" WHERE " . $this->db->formatField("WKX_resource_paraphrase.resourceId") . "=" . 
						$this->db->tidyInput($row['resourceId']) . 
					" ORDER BY " . $this->db->tidyInputClause('page_start') . ' + 0');
//					ORDER BY " . $this->db->tidyInputClause('page_start')) . " + 0";
				if($this->db->numRows($recordset2))
				{
					if($returnAfterBib)
					{
						$this->pString .= $this->makeParagraph('bibliography') . "\n";
						$returnAfterBib = FALSE;
					}
					if(trim($this->input['paraphrasesTag']))
					{
						$this->pString .= $this->rtfParagraphBlock('paraphrases');
						$this->pString .= $this->utf8_2_unicode(trim(
							$this->input['paraphrasesTag'])) . " \\par }\n";
					}
					$numElements = 0;
					while($rowT = $this->db->loopRecordSet($recordset2))
					{
						$cite = "-->  "; // resetting
						$page_start = $rowT['page_start'] ? "p." . $rowT['page_start'] : FALSE;
						$page_end = $rowT['page_end'] ? "-" . $rowT['page_end'] : FALSE;
						if($page_start && $page_end)
							$page_start = 'p' . $page_start;
						if(array_key_exists('metadataFullCite', $this->input) && $this->fullCite && $page_start)
							$page_start = $this->fullCite . ', ' . $page_start;
						else if(array_key_exists('metadataFullCite', $this->input) && $this->fullCite)
							$page_start = $this->fullCite;
						if($page_start)
							$cite = "$page_start$page_end:  ";
						if($numElements)
							for($i = 0; $i < $this->fontBlocks['paraphrases']['crBetween']; $i++)
								$this->pString .= $this->makeParagraph('paraphrases') . "\n";
						$this->pString .= $this->rtfParagraphBlock('paraphrases');
						$this->pString .= $cite . $this->utf8_2_unicode(
							$this->textFormat($rowT['text'], 
							'paraphrases')) . "\\par }";
						if(array_key_exists('paraphrasesComments', $this->input))
						{
							if($this->input['metadata'] == 1) // only my musings
								$recordset3 = $this->db->select(
									array('WKX_resource_paraphrase_comment'), 
									array('comment', 'addUserIdParaphrase'), 
									" WHERE " . $this->db->formatField('paraphraseId') . "=" . 
									$this->db->tidyInput($rowT['paraphraseId']) . 
									" AND " . 
									$this->db->formatfield("addUserIdParaphrase") . "=" . 
									$this->db->tidyInput($userId));
							else // my musings and all public musings
								$recordset3 = $this->db->select(array('WKX_resource_paraphrase_comment'),
									array('comment', 'addUserIdParaphrase'), 
									" WHERE " . $this->db->formatField('paraphraseId') . "=" . 
									$this->db->tidyInput($rowT['paraphraseId']) . 
									" AND (" . 
									$this->db->formatfield("addUserIdParaphrase") . "=" . 
									$this->db->tidyInput($userId) . 
									" OR " . 
									$this->db->formatfield("paraphrasePrivate") . "=" . 
									$this->db->tidyInput('N') . ")"
									);
							while($rowC = $this->db->loopRecordSet($recordset3))
							{
								$user = $this->user->displayUserAddEditPlain($rowC['addUserIdParaphrase'])
									. "\n";
								if(trim($this->input['paraphrasesCommentsTag']))
								{
									$this->pString .= "\n" . 
										$this->rtfParagraphBlock('paraphrases');
									$this->pString .= $this->utf8_2_unicode(trim(
										$this->input['paraphrasesCommentsTag'])) .
										"  }\n";
								}
								$this->pString .= $this->rtfParagraphBlock('paraphrases');
								$this->pString .= $this->utf8_2_unicode(
								$this->textFormat($rowC['comment'], 'paraphrases')) . 
								"  ($user)\\par }\n";
							}
						}
						$numElements++;
					}
					for($i = 0; $i < $this->fontBlocks['paraphrases']['crFollowing']; $i++)
						$this->pString .= $this->makeParagraph('paraphrases') . "\n";
					$somethingToPrint = TRUE;
				}
			}
// Do divider
			if($somethingToPrint && array_key_exists('divider', $this->input) && trim($this->input['divider']))
			{
				$this->pString .= $this->makeBlock('divider');
				$this->pString .= $this->rtfParagraphBlock('divider');
				$this->pString .= $this->utf8_2_unicode(trim($this->input['divider'])) . " \\par }" . "\n";
			}
			if($somethingToPrint)
			{
				for($i = 0; $i < $this->dividerCR[$this->input['dividerCR']]; $i++)
					$this->pString .= $this->makeParagraph('divider') . "\n";
			}
		}
	}
// Make a RTF paragraph
	function makeParagraph($type)
	{
		return "{" . $this->fontBlocks[$type]['fontBlock'] . $this->fontBlocks[$type]['fontSize'] . " \\par }";
	}
// make RTF block (justification, indents)
	function makeBlock($type)
	{
		if($type == 'divider')
			$pString = "\\qc";
		else
			$pString = "\\qj";
		$pString .= $this->fontBlocks[$type]['indentL'];
		$pString .= $this->fontBlocks[$type]['indentR'];
		return $pString . "\n";
	}
// format text with bold, italics, underline, convert newlines etc.
	function textFormat($input, $type)
	{
// remove db slashes and convert newlines
//			$input = preg_replace("/(\015?\012){2,}/", " }" . $this->makeParagraph($type) . 
//				$this->makeParagraph($type) . $this->rtfParagraphBlock($type), stripslashes($input));
			$input = stripslashes($input);
			$input = str_replace("\\", "\\\\", $input);
			$input = str_replace("{", "\\{", $input);
			$input = str_replace("}", "\\}", $input);
// For lists, remove top level tags and leave [*] as list indicator
			$input = preg_replace("/\[list.*\]/U", "__WIKINDX__NEWLINEPAR__", $input);
			$input = str_replace("[/list]", "__WIKINDX__NEWLINEPAR__", $input);
//			$input = preg_replace("/\x0D\x0A|\x0D|\x0A/", " }__WIKINDX__NEWLINEPAR__" . 
//			$this->makeParagraph($type) . $this->rtfParagraphBlock($type), $input);
// Remove certain BBCodes
			$pattern = array(
							"/\[size=.*?\](.*?)\[\/size\]/is",
							"/\[color=.*?\](.*?)\[\/color\]/is",
							"/\[float=.*?\](.*?)\[\/float\]/is",
							"/(\s*)(?<!\http:\/\/)(www\.)(\S+)/i", // watch out for 'www' in image/url tags!
							"/\[url\](.*?)\[\/url\]/is",
							"/\[url=(.*?)\](.*?)\[\/url\]/is",
							"/\[email\](.*?)\[\/email\]/is",
							"/(\s*)(ftp\.)(\S+)/i",
							"/\[img=.*?\](.*?)\[\/img\]/is",
							"/\[align=.*?\](.*?)\[\/align\]/is",
							"/\[code\](.*)\[\/code\]/is",
						);
		$change = array(
							"\\1",
							"\\1",
							"\\1",
							"\\1{\\field{\\fldinst { HYPERLINK \"http://\\2\\3\" }}{\\fldrslt {\\cs1\\ul\\cf1 \\2\\3}}}__WIKINDX__NEWLINE__",
							"{\\field{\\fldinst { HYPERLINK \"$1\" }}{\\fldrslt {\\cs1\\ul\\cf1 $1}}}__WIKINDX__NEWLINE__",
							"{\\field{\\fldinst { HYPERLINK \"$1\" }}{\\fldrslt {\\cs1\\ul\\cf1 $2}}}__WIKINDX__NEWLINE__",
							"{\\field{\\fldinst { HYPERLINK \"mailto:$1\" }}{\\fldrslt {\\cs1\\ul\\cf1 $1}}}__WIKINDX__NEWLINE__",
							"\\1{\\field{\\fldinst { HYPERLINK \"http://\\2\\3\" }}{\\fldrslt {\\cs1\\ul\\cf1 \\2\\3}}}__WIKINDX__NEWLINE__",
							"\\1",
							"\\1",
							"\\1",
						);
		$input = preg_replace($pattern, $change, $input);
// Handle images
		$input = preg_replace_callback("/\[img\](.*?)\[\/img\]/Usi",
			array($this->wprtf, "imageCallback"), $input);
// convert citations (FALSE for no hyperlink)
		$input = $this->cite->parseCitations($input, 'rtf', FALSE, TRUE);
		$pattern = array(
							"/\x0D\x0A|\x0D|\x0A/", // \r and \n
							"/\[b\](.*?)\[\/b\]/si",
							"/\[u\](.*?)\[\/u\]/si",
							"/\[i\](.*?)\[\/i\]/si",
							"/\[sup\](.*?)\[\/sup\]/si",
							"/\[sub\](.*?)\[\/sub\]/si",
						);
		$change = array(
							" }__WIKINDX__NEWLINEPAR__" . 
			$this->makeParagraph($type) . $this->rtfParagraphBlock($type), // temporary replace
							"{\\b $1}",
							"{\\ul $1}",
							"{\\i $1}",
							"{\\super $1}",
							"{\\sub $1}",
						);
		$input = preg_replace($pattern, $change, $input);
// Replace temporary newlines
		$input = str_replace("__WIKINDX__NEWLINEPAR__", "\n", $input);
		$input = str_replace("__WIKINDX__NEWLINE__", "\n", $input);
		return $input;
//		return preg_replace($this->dbFormat, $this->rtfFormat, $input);
	}
// If requested, get primary creator surname and publication year for this resource in order to add to the metadata.
	function getFullCite($resourceId, $resourceType)
	{
		$this->fullCite = '';
		$recordset = $this->db->select(array('WKX_resource_creator', 'WKX_resource_year'), 
			array('creator1', 'surname', 'prefix', 'year1', 'year2'), 
			" LEFT JOIN " . 
				$this->db->formatTable('WKX_creator') . " ON " . 
				$this->db->formatField('WKX_creator.id') . " = " . 
				$this->db->formatField('WKX_resource_creator.creator1') . 
			" WHERE " . $this->db->formatField('WKX_resource_creator.id') . " = " . 
				$this->db->tidyInput($resourceId) . 
			" AND " . $this->db->formatField('WKX_resource_year.id') . " = " . 
				$this->db->tidyInput($resourceId)
			);
		while($row = $this->db->loopRecordSet($recordset))
		{
			$creator = '';
			if($row['prefix'])
				$creator = $row['prefix'] . ' ' . $row['surname'];
			else
				$creator = $row['surname'];
			if($row['year2'] && (($resourceType == 'book') || ($resourceType == 'book_article')))
				$year = $creator ? ' ' . $row['year2'] : $row['year2'];
			else if($row['year1'])
				$year = $creator ? ' ' . $row['year1'] : $row['year1'];
			else
				$year = '';
			$this->fullCite = $creator . $year;
		}
	}
// Error handling
	function failure($error)
	{
		$this->template->setVar('body', $error);
		$pString = $this->template->process();
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $pString);
	}
// validate user input
	function checkInput()
	{
		$this->session->clearArray("exportRtf");
		$this->writeSession();
// At least one must be on
		if(!array_key_exists("exportRtf_bibliography", $this->vars) && 
			!array_key_exists("exportRtf_abstract", $this->vars) && 
			!array_key_exists("exportRtf_notes", $this->vars) && 
			!array_key_exists("exportRtf_quotes", $this->vars) && 
			!array_key_exists("exportRtf_paraphrases", $this->vars) && 
			!array_key_exists("exportRtf_musings", $this->vars))
			$this->failure($this->errors->text("inputError", "missing"));
		return $this->session->getArray("exportRtf");
	}
// write input to session
	function writeSession()
	{
		foreach($this->vars as $key => $value)
		{
			if(preg_match("/^exportRtf_/", $key))
				$temp[$key] = $value;
		}
		if(isset($temp))
		{
			$temp['exportRtf_done'] = TRUE;
			$this->session->writeArray($temp);
		}
	}
/**
         * UTF-8 to unicode
         * returns an array of unicode character codes 
         * Code adapted from opensource PHP code by Scott Reynen at:
         * http://www.randomchaos.com/document.php?source=php_and_unicode
         *
         * @parameter string $string UTF-8 encoded string
         * @return string
         */
         
	function utf8_2_unicode($string)
	{
//		return preg_replace_callback("/&#(.*);/U", array($this, 'callback'), $string);
		$unicode = array();        
		$values = array();
		$lookingFor = 1;
		for($i = 0; $i < strlen($string); $i++)
		{
			$thisValue = ord($string[$i]);
			if($thisValue < 128)
				$unicode[] = $string[$i];
			else
			{
				if(count($values) == 0)
					$lookingFor = ($thisValue < 224) ? 2 : 3;
				$values[] = $thisValue;
				if(count($values) == $lookingFor)
				{
					$number = ($lookingFor == 3) ?
						(($values[0] % 16) * 4096) + (($values[1] % 64) * 64) + ($values[2] % 64) :
						(($values[0] % 32) * 64) + ($values[1] % 64);
					$unicode[] = '\u' . $number . " ?";
					$values = array();
					$lookingFor = 1;
				}
			}
		}
		return join('', $unicode);
	}
// callback for above - no longer needed
	function callback($array)
	{
		return '\u' . $array[1] . " ?";
	}
}
?>
